<?php
/**
 * Author: xx.com
 * Date: 2019-9-5
 */
namespace Admin\Controller;

use Think\AjaxPage;
use Admin\Logic\SpellOrderLogic;
use Think\Page;

class SpellController extends BaseController
{
	public  $order_status;
	public  $pay_status;
	public  $shipping_status;
	/*
	 * 初始化操作
	 */
	public function _initialize() {
	    parent::_initialize();
	    C('TOKEN_ON',false); // 关闭表单令牌验证
	    $this->order_status = C('ORDER_STATUS');
	    $this->pay_status = C('PAY_STATUS');
	    $this->shipping_status = C('SHIPPING_STATUS');
	    // 订单 支付 发货状态
	    $this->assign('order_status',$this->order_status);
	    $this->assign('pay_status',$this->pay_status);
	    $this->assign('shipping_status',$this->shipping_status);
	}
	
    /**
     *  商品列表
     */
    public function goodsList()
    {
       
        $this->display();
    }
    
    /**
     *  商品列表
     */
    public function ajaxGoodsList()
    {
        $where = ' 1 = 1 '; // 搜索条件
        (I('is_on_sale') !== '') && $where = "$where and is_on_sale = ".I('is_on_sale') ;
        // 关键词搜索
        $key_word = I('key_word') ? trim(I('key_word')) : '';
        if ($key_word) {
            $where = "$where and (goods_name like '%$key_word%')" ;
        }
        
        $model = M('spell_goods');
        $count = $model->where($where)->count();
        $Page = new AjaxPage($count, 10);
        /**  搜索条件下 分页赋值
         * foreach($condition as $key=>$val) {
         * $Page->parameter[$key]   =   urlencode($val);
         * }
         */
        $show = $Page->show();
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        $goodsList = $model->where($where)->order($order_str)->limit($Page->firstRow . ',' . $Page->listRows)->select();

        $this->assign('goodsList', $goodsList);
        $this->assign('page', $show);// 赋值分页输出
        $this->display();
    }


    /**
         * 添加修改商品
         */
    public function addEditGoods()
    {
        $Goods = D('SpellGoods'); //
            $type = $_POST['spell_goods_id'] > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新
            //ajax提交验证
            if (($_GET['is_ajax'] == 1) && IS_POST) {
                C('TOKEN_ON', false);
                if (!$Goods->create(null, $type)) {// 根据表单提交的POST数据创建数据对象
                    //  编辑
                    $error = $Goods->getError();
                    $error_msg = array_values($error);
                    $return_arr = array(
                        'status' => -1,
                        'msg' => $error_msg[0],
                        'data' => $error,
                    );
                    $this->ajaxReturn($return_arr);
                } else {
                    //获取当前登录人的信息
                    //  form表单提交
                    //              C('TOKEN_ON',true);
                    // p($_POST);die;

                    if ($type == 2) {
                        $goods_id = $_POST['spell_goods_id'];
    
                        $goodsInfo = M('spell_goods')->where([
                            "spell_goods_id" => $goods_id
                        ])->field("spell_goods_id")->find();
    
                        if (!$goodsInfo) {
                            return $this->error("商品不存在");
                        }
    
                       
                        $Goods->save(); // 写入数据到数据库
                    } else {
                        $goods_id = $insert_id = $Goods->add(); // 写入数据到数据库
                    }
                    
                    $return_arr = array(
                        'status' => 1,
                        'msg' => '操作成功',
                        'data' => array('url' => U('Admin/Spell/goodsList')),
                    );
                    $this->ajaxReturn($return_arr);
                }
            }
    
        $goodsInfo = M('spell_goods')->where('spell_goods_id=' . I('GET.id', 0))->find();
    
        $this->assign('goodsInfo', $goodsInfo);  // 商品详情
            $this->display('_goods');
    }
          
    
        
    /**
     * 删除商品
     */
    public function delGoods()
    {
        $goods_id = $_GET['id'];
        $error = '';

        $goodsInfo = M("spell_goods")->where('spell_goods_id ='.$goods_id)->find();

        if (!$goodsInfo) {
            $this->returnInfo(-1, "商品不存在");
        }

        // 判断此商品是否有订单
        $c1 = M('spell_order')->where("spell_goods_id = $goods_id")->count('1');
        $c1 && $error .= '此商品有订单,不得删除! <br/>';
		
        // 判断此商品是否有进行的活动
        $c2 = M('spell_project')->where("spell_goods_id = $goods_id")->count('1');
        $c2 && $error .= '此商品有活动,不得删除! <br/>';
        
        
        if ($error) {
            $return_arr = array('status' => -1,'msg' =>$error,'data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);
            $this->ajaxReturn($return_arr);
        }
        
        // 删除此商品
        M("integral_goods")->where('spell_goods_id ='.$goods_id)->delete();  //商品表
        
        $return_arr = array('status' => 1,'msg' => '操作成功','data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);
        $this->ajaxReturn($return_arr);
    }
	
	/**
	 *  活动列表
	 */
	public function projectList()
	{
	   
	    $this->display();
	}
	
	/**
	 *  活动列表
	 */
	public function ajaxProjectList()
	{
	    $where = ' 1 = 1 '; // 搜索条件
	    
	    
	    $model = M('spell_project');
	    $count = $model->where($where)->count();
	    $Page = new AjaxPage($count, 10);
	   
	    $show = $Page->show();
	    $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
	    $projectList = $model->where($where)->order($order_str)->limit($Page->firstRow . ',' . $Page->listRows)->select();
		foreach($projectList as $k => &$v){
			// 创建人信息
			$v['user_data'] = M('users')->where(['user_id'=>$v['user_id']])->find();
			// 查询参与人数
			$v['user_count'] = M('spell_project_user')->where(['spell_project_id'=>$v['spell_project_id']])->count();
			// 商品信息
			$v['goods_data'] = M('spell_goods')->where(['spell_goods_id'=>$v['spell_goods_id']])->find();
			
		}
	    $this->assign('projectList', $projectList);
	    $this->assign('page', $show);// 赋值分页输出
	    $this->display();
	}
	
	/**
	 * 删除活动
	 */
	public function delProject()
	{
	    $goods_id = $_GET['id'];
	    $error = '';
	
	    $goodsInfo = M("spell_project")->where('spell_project_id ='.$goods_id)->find();
	
	    if (!$goodsInfo) {
	        $this->returnInfo(-1, "活动不存在");
	    }
	
	    
	    // 删除此活动
	    M("spell_project")->where('spell_project_id ='.$goods_id)->delete();  //
	    M("spell_project_user")->where('spell_project_id ='.$goods_id)->delete();  //
	    M("spell_project_point_log")->where('spell_project_id ='.$goods_id)->delete();  //
	    M("spell_project_user_skill")->where('spell_project_id ='.$goods_id)->delete();  //
	    
	    $return_arr = array('status' => 1,'msg' => '操作成功','data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);
	    $this->ajaxReturn($return_arr);
	}
	
	
	/*
	 *订单首页
	 */
	public function index(){
		$begin = date('Y/m/d',(time()-30*60*60*24));//30天前
		$end = date('Y/m/d',strtotime('+1 days')); 	
		$this->assign('timegap',$begin.'-'.$end);
	    $this->display();
	}
	
	/*
	 *Ajax订单首页
	 */
	public function ajaxindex(){
	    $orderLogic = new SpellOrderLogic();       
	    $timegap = I('timegap');
	    if($timegap){
	    	$gap = explode('-', $timegap);
	    	$begin = strtotime($gap[0]);
	    	$end = strtotime($gap[1]);
	    }
	    // 搜索条件
	    $condition = array();
	    I('consignee') ? $condition['consignee'] = trim(I('consignee')) : false;
	    if($begin && $end){
	    	$condition['add_time'] = array('between',"$begin,$end");
	    }
	    I('order_sn') ? $condition['order_sn'] = trim(I('order_sn')) : false;
	    I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
	    I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
	    I('pay_code') != '' ? $condition['pay_code'] = I('pay_code') : false;
	    I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
	    I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;
	    $sort_order = I('order_by','DESC').' '.I('sort');
	    $condition['parent_sn'] = ["neq","0"];	
	    $count = M('spell_order')->where($condition)->count();
	    $Page  = new AjaxPage($count,10);
	    //  搜索条件下 分页赋值
	    foreach($condition as $key=>$val) {
	        $Page->parameter[$key]   =  urlencode($val);
	    }
	    $show = $Page->show();
	    //获取订单列表
	
	    $orderList = $orderLogic->getOrderList($condition,$sort_order,$Page->firstRow,$Page->listRows);
	
	    $this->assign('orderList',$orderList);
	    $this->assign('page',$show);// 赋值分页输出
	    $this->display('ajaxindex'.($condition['is_groupbuy'] > 0 ? $condition['is_groupbuy'] : ''));
	}
	
	/**
	 * 订单详情
	 * @param int $id 订单id
	 */
	public function detail($order_id)
	{
	    $orderLogic = new SpellOrderLogic();
	    $order = $orderLogic->getOrderInfo($order_id);
	// p($order);die;
	   
	    $orderGoods = $orderLogic->getOrderGoods($order['spell_goods_id']);
		// p($orderGoods);
	    $button = $orderLogic->getOrderButton($order);
	    $this->assign('order',$order);
	    $this->assign('orderGoods',$orderGoods);
	    $split = count($orderGoods) >1 ? 1 : 0;
	    foreach ($orderGoods as $val){
	    	if($val['goods_num']>1){
	    		$split = 1;
	    	}
	    }
	    $this->assign('split',$split);
	    $this->assign('button',$button);
	    $this->display();
	}
	
	/**
	 * 点击去发货
	 */
	public function delivery_info(){
	    $config = tpCache('shopping');
		$order_id = I('order_id');
		$orderLogic = new SpellOrderLogic();
	    $order = $orderLogic->getOrderInfo($order_id);	
		$orderGoods = $orderLogic->getOrderGoods($order['spell_goods_id']);
		
	    $shipping_list = M('plugin')->where(array('status'=>1,'type'=>'shipping'))->select();
		$this->assign('order',$order);
		$this->assign('orderGoods',$orderGoods);
	    $this->assign('shipping_list', $shipping_list);
	    $this->assign('config', $config);
		$this->display();
	}
	
	/**
	 * 生成发货单
	 */
	public function deliveryHandle(){
	    $orderLogic = new SpellOrderLogic();
		$data = I('post.');
		$res = $orderLogic->deliveryHandle($data);
		if($res){
			$this->success('操作成功',U('Admin/Spell/delivery_info',array('order_id'=>$data['order_id'])));
		}else{
			$this->success('操作失败',U('Admin/Spell/delivery_info',array('order_id'=>$data['order_id'])));
		}
	}
	
	/**
	 * 订单操作
	 * @param $id
	 */
	public function order_action(){    	
	    $orderLogic = new SpellOrderLogic();
	    $action = I('get.type');
	    $order_id = I('get.order_id');
	    if($action && $order_id){
	
	        $order = $orderLogic->getOrderInfo($order_id);
	
	        try{
	            $a = $orderLogic->orderProcessHandle($order_id,$action);
	            $res  = true;
	        }catch(\Exception $e)
	        {
	            $this->error($e->getMessage());
	        }
	    	
	
	    	 if($res && $a){
	    	 	exit(json_encode(array('status' => 1,'msg' => '操作成功')));
	    	 }else{
	    	 	exit(json_encode(array('status' => 0,'msg' => '操作失败')));
	    	 }
	    }else{
	    	$this->error('参数错误',U('Admin/Spell/detail',array('order_id'=>$order_id)));
	    }
	}
    
}
